package com.alibaba.user.service.impl;

import com.alibaba.basic.dto.LoginDto;
import com.alibaba.basic.exception.BusinessException;
import com.alibaba.basic.jwt.JwtUtils;
import com.alibaba.basic.jwt.LoginData;
import com.alibaba.basic.jwt.RsaUtils;
import com.alibaba.basic.service.impl.BaseServiceImpl;
import com.alibaba.basic.util.AjaxResult;
import com.alibaba.basic.util.HttpUtil;
import com.alibaba.basic.util.Md5Utils;
import com.alibaba.basic.util.StrUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.org.mapper.EmployeeMapper;
import com.alibaba.system.domain.Menu;
import com.alibaba.user.constant.WxConstants;
import com.alibaba.user.domain.Logininfo;
import com.alibaba.user.domain.User;
import com.alibaba.user.domain.Wxuser;
import com.alibaba.user.mapper.LogininfoMapper;
import com.alibaba.user.mapper.UserMapper;
import com.alibaba.user.mapper.WxuserMapper;
import com.alibaba.user.service.ILogininfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private  RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String checkPass = loginDto.getCheckPass();

        // 一。空值校验
        if (StringUtils.isEmpty(account) ||StringUtils.isEmpty(checkPass) ){
            throw  new BusinessException("信息不能为空");
        }

        // 二。账号校验
         Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null){
            throw  new BusinessException("账号或者密码错误");
        }

        // 三。检验 密码 加盐加密
        // 前端输入的密码加盐加密
        String inputPwd = Md5Utils.encrypByMd5(checkPass + logininfo.getSalt());
        if ( !inputPwd.equals(logininfo.getPassword())){
            throw  new BusinessException("账号或者密码错误");
        }

        // 四。校验是否被禁用
        if (!logininfo.getDisable())
            throw  new BusinessException("该账号被禁用，请联系管理员");

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);


//        // 五。生成token 并将token保存到redis 数据库设置30分钟有效
//        String token = UUID.randomUUID().toString();
//        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
//
//        // 六。封住返回值
//        Map<String, Object> map = new HashMap<>();
//        map.put("token",token);
//        logininfo.setSalt(null);
//        logininfo.setPassword(null);
//        map.put("logininfo",logininfo);

        return map;
    }

    @Override
    public AjaxResult wechatLogin(String code) {
        //1.根据code发送第二个请求：httpUtil，返回json格式字符串
        //a.准备第二个请求和参数
        String url = WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID).replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        //调用工具类发送请求，返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);
        //2.使用fastJson进行处理：获取token，openid
        JSONObject obj = JSONObject.parseObject(jsonStr);
        String access_token = obj.getString("access_token");
        String openid = obj.getString("openid");

        //3.根据openid去查询t_wxuser表
        Wxuser wxuser = wxuserMapper.findByOpenid(openid);
        //3.1.查到了=以前扫过码 = 直接免密登陆【不需要在页面中输入用户名和密码就可以登陆】
        //如果通过openid查询到了微信用户对象
        if(wxuser!=null){
            //只要有wxuser，就一定会绑定user_id
            User user = userMapper.findById(wxuser.getUserId());
            if(user!=null){ //并且关联的User对象也有值 - 绑定了 - 后续扫码 - 免密登陆
                Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());

                Map<String, Object> map = loginSuccessJwtHandler(logininfo);


                return AjaxResult.me().setResultObj(map);
            }
        }

        //3.2.如果没有查到 = 响应给前端token，openid，前端跳转到绑定页面
        return AjaxResult.me().setSuccess(false).setResultObj("?access_token="+access_token + "&" + "openid="+openid);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");



        // 一。空值校验
        if (StringUtils.isEmpty(phone)|| StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空");
        }
        // 一 。检验微信绑定是否失效
        if (StringUtils.isEmpty(accessToken)|| StringUtils.isEmpty(openId)){
            throw new BusinessException("绑定失效，请重新扫码");
        }
        
        // 二。手机验证码校验，是否过期。验证码是否正确
        Object phoneCode = redisTemplate.opsForValue().get("binder:" + phone);
        if (phoneCode==null){
            throw new BusinessException("手机号码过期");
        }
        if (!phoneCode.toString().split(":")[0].equals(verifyCode)){
            throw new BusinessException("手机验证码不正确");
        }


        // 三。组装第三个请求的url地址
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        
        // 四。发送http请求，并返回json格式的字符串
        String jsonStr = HttpUtil.httpGet(url);

        // 五，将json格式的字符串转换为json对象，并转换一个wxuser
         Wxuser wxuser = jsonStr2Wxuser(jsonStr);

        // 六，根据电话获取【以前注册过但是没有绑定微信】或者新建user对象【logininfo对象添加】，并将对象添加到user库
        User user = userMapper.findByPhone(phone);
        if (user==null){
            // 没有注册过，创建user对象
            user = phone2User(phone);
            // 创建logininfo对象
            Logininfo logininfo = user2Logininfo(user);
            // 保存到logininfo中
            logininfoMapper.add(logininfo);
            user.setLogininfoId(logininfo.getId());
            // 添加到user中
          userMapper.add(user);
        }
        // 七，将user_id添加到t-wxuser对象中并将wxuser对象添加到数据库
        wxuser.setUserId(user.getId());

        // 八，免密登录
        Logininfo logininfoTemp= logininfoMapper.findById(user.getLogininfoId());

        Map<String, Object> mapTemp = loginSuccessJwtHandler(logininfoTemp);
        return AjaxResult.me().setResultObj(mapTemp);
    }

    private Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        //目的：获取四个数据：jwtToken，logininfo，当前登录人的权限，当前登录人的菜单
        //细节：管理员登录，用户登录【当前登录人的权限不需要，当前登录人的菜单不需要】
        Map<String,Object> map = new HashMap<>();
        LoginData loginData = new LoginData();
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);
        if(logininfo.getType() == 0){//管理员
            //1.获取当前登录人的权限 - 昨天已经写过了
            List<String> permissions = employeeMapper.getSns(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);
            //2.获取当前登录人的菜单 - 麻烦【四张表 + 自连接】
            List<Menu> menus = employeeMapper.getMenus(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }
        try {
            //3.使用私钥加密【loginData = logininfo+当前登录人的权限+当前登录人的菜单】成一个jwtToken
            PrivateKey privateKey = RsaUtils.getPrivateKey(LogininfoServiceImpl.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String token = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //4.将以上四个数据添加到Map进行返回
        return map;
    }
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        // 生成一个随机的6位数密码
        String pwd = StrUtils.getComplexRandomString(6);
        String md5 = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setNickname(obj.getString("nickname"));
        wxuser.setSex(Integer.parseInt(obj.getString("sex")));
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("unionid"));
        return wxuser;
    }
}
